﻿//按Enter移到下一個控制項
$(document).unbind('keydown').bind('keydown', function (event) {
    var doPrevent = false;
    if (event.keyCode === 8) {
        var d = event.srcElement || event.target;
        if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' || d.type.toUpperCase() === 'PASSWORD' || d.type.toUpperCase() === 'FILE'))
             || d.tagName.toUpperCase() === 'TEXTAREA') {
            doPrevent = d.readOnly || d.disabled;
        }
        else {
            doPrevent = true;
        }
    }

    if (doPrevent) {
        event.preventDefault();
    }
});

document.onkeydown = function (evt) {
    var isie = (document.all) ? true : false;
    var key;
    var srcobj;
    // if the agent is an IE browser, it's easy to do this.
    if (isie) {
        key = event.keyCode;
        srcobj = event.srcElement;
    }
    else {
        key = evt.which;
        srcobj = evt.target;
    }
    if (key == 13 && srcobj.type != 'button' && srcobj.type != 'submit' && srcobj.type != 'reset' && srcobj.type != 'textarea' && srcobj.type != '') {
        if (isie)
        {
            var Element = GetEvent(evt);
            ObjCtrl = $(":input[type!=hidden],select:enabled");
            if (ObjCtrl.length != 0) {
                for (var CtrlCount = 0; CtrlCount < ObjCtrl.length; CtrlCount++) {
                    if (ObjCtrl[CtrlCount].id == Element.id.toString()) {
                        for (var subCtrlCount = CtrlCount + 1; subCtrlCount < ObjCtrl.length; subCtrlCount++) {
                            var m_readOnly = false;
                            if (ObjCtrl[subCtrlCount].readOnly == undefined)
                                m_readOnly = false;
                            else
                                m_readOnly = ObjCtrl[subCtrlCount].readOnly;
                            if (!ObjCtrl[subCtrlCount].disabled && m_readOnly == false && ObjCtrl[subCtrlCount].type != "button" && ObjCtrl[subCtrlCount].type != "checkbox") {
                                ObjCtrl[subCtrlCount].focus();
                                return false;
                            }
                        }

                    }
                }
            }
        }
        else {
            var el = getNextElement(evt.target);
            if (el.type != 'hidden')
                ;   //nothing to do here.
            else
                while (el.type == 'hidden')
                    el = getNextElement(el);
            if (!el)
                return false;
            else
                el.focus();
        }
    }
}


//取得Array Index筆數
var getObjIndex = function (array, attr, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i].hasOwnProperty(attr) && array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}
//網頁遮罩專用
var g_Mask = false;
function DoBlock(p_Fun) {
    //取得submit 按鈕ID
    var m_BtnID = GetEvent(event).id;
    //執行遮罩
    $.blockUI({
        fadeIn: 700,
        fadeOut: 700,
        css: {
            border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: .5,
            color: '#fff'
        },
        onBlock: function () {
            if (!g_Mask) {
                //執行檢核Function
                g_Mask = p_Fun.Fun();
                //判斷檢核是否通過
                if (g_Mask)
                    $('#' + m_BtnID)[0].click();//執行submit
                else
                    $.unblockUI();//關閉遮罩
            }
            return true;
        }

    });

}

//開啟預覽報表
function OpenReport(p_Url, p_Name, p_dialogStr, p_isReplace)
{
    p_isReplace = p_isReplace == undefined ? false : true;
    if (IsIOS())
        window.open(p_Url, "", "", p_isReplace);
    else
        window.showModalDialog(p_Url, p_Name, p_dialogStr, p_isReplace);
}
//按鈕Disable
function BtnDisable(p_BtnID)
{
    $("#" + p_BtnID).attr('class', 'BtnOff');
    $("#" + p_BtnID).unbind("click");
    $("#" + p_BtnID).bind("click", function ()
    {
        return false;
    });
}
//判斷瀏覽器是否為IOS系統
function IsIOS()
{
    var deviceAgent = navigator.userAgent;
    return deviceAgent.toLowerCase().match(/(iphone|ipod|ipad)/);
}
//首頁開啟功能頁
function OpenUrl(p_URL)
{
    var d = new Date();
    var m_now = d.getTime();
    var deviceAgent = navigator.userAgent;
    var ios = deviceAgent.toLowerCase().match(/(iphone|ipod|ipad)/);
    if (ios)
        setTimeout("window.open('" + p_URL + "?d=" + m_now + "', '_blank');", 100);
    else
        window.open(p_URL + "?d=" + m_now, "_blank");
}



//開啟查詢式窗 (控制項ID,查詢視窗ID,寬度,高度,查詢條件,是否預設查詢)
function OpenQueryCtrl(p_CtrlID, p_QueryID, p_Width, p_Height, p_ObjOfQuery, p_IsQuery) {
    p_CtrlID = p_CtrlID.replace("img_", "");
    if ($("#div_" + p_CtrlID).length == 0) {
        $("#Wrapper").append("<div  id='div_" + p_CtrlID + "'><iframe style='display:none' id='fra_" + p_CtrlID + "' src=''></iframe></div>")
    }
    var m_IsQuery = "N";
    if (p_IsQuery)
        m_IsQuery = "Y";
    $("#div_" + p_CtrlID).dialog({
        autoOpen: false,
        modal: true,
        height: p_Height,
        width: p_Width,
        close: function (e) {
            $('#fra_' + p_CtrlID).attr('src', '');
            $('#fra_' + p_CtrlID).hide();
        },
        open: function (ev, ui) {
            $('#fra_' + p_CtrlID).show();
            $('#fra_' + p_CtrlID).width((p_Width - 50).toString() + "px");
            $('#fra_' + p_CtrlID).height((p_Height - 70).toString() + "px");
            var strObjOfQuery = JSON.stringify(p_ObjOfQuery);
            $('#fra_' + p_CtrlID).attr('src', '../Query/CommonQuery.aspx?IsQuery=' + m_IsQuery + '&CtrlID=' + p_CtrlID + '&QueryID=' + p_QueryID + '&Param=' + strObjOfQuery);

        }
    });
    $('#div_' + p_CtrlID).dialog('open');
}
//開啟新一頁(DIV)   (抬頭,寬度,高度,查詢條件,QueryString)
function OpenDivDialg(p_Title, p_Width, p_Height, p_ObjOfQuery, p_Path) {
    if ($("#fra_DivDialg").length == 0) {
        $("#Wrapper").append("<div title='" + p_Title + "' id='DivDialg'><iframe style='display:none' id='fra_DivDialg' src=''></iframe></div>")
    }
    $("#DivDialg").dialog({
        autoOpen: false,
        modal: true,
        height: p_Height,
        width: p_Width,
        close: function (e) {
            $('#fra_DivDialg').attr('src', '');
            $('#fra_DivDialg').hide();
        },
        open: function (ev, ui) {
            $('#fra_DivDialg').show();
            $('#fra_DivDialg').width((p_Width - 50).toString() + "px");
            $('#fra_DivDialg').height((p_Height - 70).toString() + "px");
            var strObjOfQuery = JSON.stringify(p_ObjOfQuery);
            p_Path += (p_Path.indexOf("?") == -1) ? "?" : "&";
            $('#fra_DivDialg').attr('src', p_Path + 'Param=' + strObjOfQuery);
        }
    });
    $('#DivDialg').dialog('open');
}


//刪除暫存檔
function Del_Temp(p_SEQ,p_TableName)
{
    //刪除 
    $.ajax({
        type: "POST",
        async: false,
        url: "../Common/BLL.aspx/Delete_TEMPFILE",
        data: "{ P_SEQ : '" + p_SEQ + "',P_TABLENAME : '" + p_TableName + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (xmlHttpRequest, error) {
            var m_ErrMessage = xmlHttpRequest.responseText;
            alert(m_ErrMessage);
        },
        success: function (data) {
            var m_DEL_SUCCESS = data.d;

            if (m_DEL_SUCCESS[0]["ReturnCode"] != "000") {
                alert(m_DEL_SUCCESS[0]["Message"].toString());
            }
        }
    });

}

//取得序號
function getSEQ()
{
    var m_SEQ = "";
    $.ajax({
        type: "POST",
        async: false,
        url: "../Common/BLL.aspx/GetSEQ",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (xmlHttpRequest, error) {
            var m_ErrMessage = xmlHttpRequest.responseText;
            alert(m_ErrMessage);
        },
        success: function (data) {
            m_SEQ = data.d[0].SEQ;
        }
    });

    return m_SEQ;
}

//移至下個控制項
function getNextElement(field) {
    var form = field.form;
    for (var e = 0; e < form.elements.length; e++) {
        if (field == form.elements[e])
            break;
    }
    return form.elements[++e % form.elements.length];
}
//取得Event
function GetEvent(e) {
    return e.target ? e.target : $(event.srcElement || event.target).context;
}

//初始Form需停再第一個可以Key in的控制項
function Pointfocus(p_TargetDiv) {
    try {
        if (p_TargetDiv != undefined) {
            p_TargetDiv = "." + p_TargetDiv + " ";
        }
        else {
            p_TargetDiv = ".divMain ";
        }
        var ObjCtrl = $(p_TargetDiv + ":input");
        if (ObjCtrl.length != 0) {
            for (var CtrlCount = 0; CtrlCount < ObjCtrl.length; CtrlCount++) {
                if (!ObjCtrl[CtrlCount].disabled && ObjCtrl[CtrlCount].type != "button") {
                    $("#" + ObjCtrl[CtrlCount].id)[0].focus();
                    break;
                }
            }
        }
    }
    catch (e) {
        //alert("Error : Pointfocus()" + e.message);
    }
}

//處理Enter事件 Enter跳到下個控制項
function EventHandler_KeyDown() {
    try {
        Event_KeyDown(event);
    }
    catch (e) {
        return true;
    }
}

//日期區間公用FUNCTION
function DateRange(p_From, p_To, p_DateCount) {
    $(function () {
        if (!p_DateCount)
            p_DateCount = 2;
        $("#" + p_From).datepicker({
            changeMonth: true,
            changeYear: true,
            numberOfMonths: p_DateCount,
            onClose: function (selectedDate) {
                $("#" + p_To).datepicker("option", "minDate", selectedDate);
            }
        });
        $("#" + p_To).datepicker({
            changeMonth: true,
            numberOfMonths: p_DateCount,
            onClose: function (selectedDate) {
                $("#" + p_From).datepicker({ dateFormat: 'yymmdd' });
                $("#" + p_From).datepicker("option", "maxDate", selectedDate);
            }
        });
    });
}


//新增空白欄位Jquery版
function AddDetailList_N(DetailTable, seq, rows, p_Table_ID) {
    var m_Table_ID = "DetailTable";
    if (p_Table_ID) {
        m_Table_ID = p_Table_ID;
    }
    if (rows == "" || rows == undefined)
        //2005/4/20以便沒傳ROWS也可以增加空白欄位by samantha
    {
        rows = 10;
    }
    var selectedIndex = $("#" + m_Table_ID + " tr").length;
    var rowCount = $("#" + m_Table_ID + " tr").length;
    for (i = 0; i < rows; i++) {
        var TR_Html = "";
        var row = selectedIndex - 1
        var Html = "";
        $("#" + m_Table_ID + " tr:first td").each(function (td_index) {
            Html += "<td>" + $(this)[0].innerHTML + "</td>";

            $.each($(this)[0].children, function (index, m_ctrl) {
                if (m_ctrl.name != "M") {
                    if (m_ctrl.tagName != "A") {
                        Html = Html.replaceAll(m_ctrl.name, m_ctrl.id.replace("0", "") + (rowCount + i).toString())
                        switch (m_ctrl.type) {
                            case "checkbox":
                                Html = Html.replace("CHECKED", "");
                                Html = Html.replace("disabled=\"\"", "");
                                if (m_ctrl.style.background != "")
                                    m_ctrl.style.background = "";
                                break;
                            case "hidden":
                                if (m_ctrl.value != "") {
                                    value = "value=\"" + m_ctrl.value + "\"";
                                    Html = Html.replace(value, "value=\"\"");
                                    Html = Html.replace("disabled=\"\"", "");
                                    if (m_ctrl.style.background != "")
                                        m_ctrl.style.background = "";

                                }
                                break;
                            case "text":
                                if (td_index == seq) {
                                    value = "value=\"" + m_ctrl.value + "\"";
                                    Html = Html.replace(value, "value=\"" + (rowCount + i + 1).toString() + "\"");
                                    Html = Html.replace("disabled=\"\"", "");
                                    if (m_ctrl.style.background != "")
                                        m_ctrl.style.background = "";
                                }
                                else {
                                    if (m_ctrl.value != "") {
                                        value = "value=\"" + m_ctrl.value + "\"";
                                        Html = Html.replace(value, "value=\"\"");
                                        Html = Html.replace("disabled=\"\"", "");
                                        if (m_ctrl.style.background != "")
                                            m_ctrl.style.background = "";

                                    }
                                }
                                break;
                            case "select-one":
                                if (m_ctrl.value != "") {
                                    value = "selected"
                                    Html = Html.replace(value, "")
                                }
                                break;
                        }
                    }
                    else {
                        if (m_ctrl.children.length > 0) {
                            pr_row = rows - 1;
                            value = "(" + pr_row + ")"
                            value1 = "(" + rows + ")"
                            Html = Html.replace(value, value1)
                        }
                        else {
                            Html = ""//hyperlink清為空白
                        }
                    }
                }
                else {
                    if (m_ctrl.value != "") {
                        value = "value=\"" + m_ctrl.value + "\"";
                        Html = Html.replace(value, "value=A")
                    }
                }
            });


            if ($(this)[0].children.length == 0) {
                Html = ""
            }
        });
        TR_Html = "<tr> " + Html + "</tr>";
        $("#" + m_Table_ID).append(TR_Html);


        $.each($("#" + m_Table_ID + " tr")[rowCount + i].children, function (index, m_Td) {
            $.each(m_Td.children, function (index, m_ctrl) {
                var m = 1;
                if ($("#" + m_ctrl.id).attr("class")) {
                    if ($("#" + m_ctrl.id).attr("class").indexOf("hasDatepicker") != -1) {
                        $("#" + m_ctrl.id).attr("class", "");
                        $("#" + m_ctrl.id).datepicker({
                            changeMonth: true,
                            changeYear: true,
                            showButtonPanel: true
                        });
                    }
                }
            });
        });
    }
}


//新增空白欄位舊版
function AddDetailList(DetailTable, seq, rows) {
    try {
        if (rows == "" || rows == undefined)
            //2005/4/20以便沒傳ROWS也可以增加空白欄位by samantha
        {
            rows = 10;
        }
        var selectedIndex = DetailTable.rows.length;

        for (i = 0; i < rows; i++) {

            var DestRow = DetailTable.insertRow();
            AddDetailCell(DestRow, DetailTable.rows[0].cells.length);
            var row = DetailTable.rows.length - 1
            for (j = 0; j < DetailTable.rows[0].cells.length; j++) {

                HTML = DetailTable.rows[row - 1].cells[j].innerHTML
                //if (j != seq)//seq不修改其id
                //{
                for (k = 0; k < DetailTable.rows[row - 1].cells[j].children.length; k++) {
                    //2010/07/15 modify by Ray prevent error
                    if (typeof DetailTable.rows[row - 1].cells[j].children[k].name === 'undefined')
                        continue;

                    if ((DetailTable.rows[row - 1].cells[j].children[k].name).substr(0, 1) != 'M') {
                        if (DetailTable.rows[row - 1].cells[j].children[k].tagName != "A") //hyperlink
                        {
                            HTML = HTML.replace(DetailTable.rows[row - 1].cells[j].children[k].name, DetailTable.rows[row - 1].cells[j].children[k].id.substr(0, DetailTable.rows[row - 1].cells[j].children[k].id.lastIndexOf((row - 1).toString())) + row.toString());
                            HTML = HTML.replace(DetailTable.rows[row - 1].cells[j].children[k].id, DetailTable.rows[row - 1].cells[j].children[k].id.substr(0, DetailTable.rows[row - 1].cells[j].children[k].id.lastIndexOf((row - 1).toString())) + row.toString());

                            switch (DetailTable.rows[row - 1].cells[j].children[k].type) {
                                case "checkbox":
                                    HTML = HTML.replace("CHECKED", ""); break;
                                case "hidden":
                                    if (DetailTable.rows[row - 1].cells[j].children[k].value != "") {
                                        value = "value=" + DetailTable.rows[row - 1].cells[j].children[k].value
                                        HTML = HTML.replace(value, "")
                                    }
                                    break;
                                case "text":
                                    if (DetailTable.rows[row - 1].cells[j].children[k].value != "") {
                                        value = "value=" + DetailTable.rows[row - 1].cells[j].children[k].value
                                        HTML = HTML.replace(value, "")
                                    }
                                    break;
                                case "select-one":
                                    if (DetailTable.rows[row - 1].cells[j].children[k].value != "") {
                                        value = "selected"
                                        HTML = HTML.replace(value, "")
                                    }
                                    break;
                            }
                        }
                        else {
                            if (DetailTable.rows[row - 1].cells[j].children[k].children.length > 0) {
                                pr_row = rows - 1;
                                value = "(" + pr_row + ")"
                                value1 = "(" + rows + ")"
                                HTML = HTML.replace(value, value1)
                            }
                            else {
                                HTML = ""//hyperlink清為空白
                            }
                        }
                    }
                    else {
                        if (DetailTable.rows[row - 1].cells[j].children[k].value != "") {
                            value = "value=" + DetailTable.rows[row - 1].cells[j].children[k].value
                            HTML = HTML.replace(value, "value=A")
                        }

                    }

                }
                //}
                if (DetailTable.rows[row - 1].cells[j].children.length == 0) {
                    HTML = ""
                }
                DestRow.cells[j].innerHTML = HTML.replace("font-size:" + i.toString() + "px;", "");
                DestRow.cells[j].align = DetailTable.rows[row - 1].cells[j].align
                //修改為了，checkbox打勾時，所有欄位為readony時，再按下新增空白欄位的button，必需將欄位屬性改成可輸入，by vicky 94.5.2
                for (k = 0; k < DestRow.cells[j].children.length; k++) {
                    if (DestRow.cells[j].children[k].type == 'text' || DestRow.cells[j].children[k].type == 'number') {
                        if ($("#" + DestRow.cells[j].children[k].id).attr("class").indexOf("hasDatepicker") != -1) {
                            $("#" + DestRow.cells[j].children[k].id).attr("class", "");
                            $("#" + DestRow.cells[j].children[k].id).datepicker({
                                changeMonth: true,
                                changeYear: true,
                                showButtonPanel: true
                            });
                        }
                        DestRow.cells[j].children[k].value = ""
                        DestRow.cells[j].children[k].style.background = "#FFFFFF";
                        if ((DestRow.cells[j].children[k].className == 'text' || DestRow.cells[j].children[k].className == 'number') && DestRow.cells[j].children[k].readOnly) {
                            DestRow.cells[j].children[k].readOnly = false
                        }
                    }

                }

            }
            if (seq != undefined) {
                if (seq.toString() != "") {

                    DetailTable.rows[row].cells[parseInt(seq)].children[0].value = parseInt(DetailTable.rows[row - 1].cells[parseInt(seq)].children[0].value) + 1

                }
            }
        }
    }
    catch (e) {
        ShowError(e.message);
    }
    finally {

    }
}

/*
	函式功能: 建立表格中的Cells
	傳入值 : Table
	傳出值 : void
*/
function AddDetailCell(DestRow, cells) {
    try {
        for (j = 0; j < cells; j++) {
            DestRow.insertCell();
            DestRow.cells[j].className = "detail";
        }
    }
    catch (e) {
        ShowError(e.message);
    }
}

//新增下拉選單項目
function AddDrpItem(Obj, Value, Text) {
    Obj.append($("<option></option>").attr("value", Value).text(Text));
}


//控制錯誤資料及秀錯誤訊息
function ShowError(Message) {
    alert(Message);
}

function AddCboItem(Obj, Text, Text1) {
    var opt = document.createElement("OPTION");
    opt.value = Text;
    opt.text = Text1;
    Obj.options.add(opt);
}
//---------------------------------------------------------------------------------------

function ClearCob(Obj) {
    while (Obj.options.length != 0) {
        Obj.options.remove(0);
    }
}

function SelectedByValue(obj_name, obj_value) {
    var i = 0;
    var f = document.forms[0];
    for (i = 0; i < f.elements[obj_name].length; i++) {

        if ((f.elements[obj_name].options[i].value) == (obj_value)) {

            f.elements[obj_name].options[i].selected = true;
            break;
        } else {
            continue;
        }
    }
}

//---------------------------------------------------------------------------------------
/* 鎖定Button防止重複Submit   Creator By Titan*/
// 傳入參數說明 : elem 固定鎖定該物件，當網頁物件過多時使用，不傳時則鎖定網頁所有控制項 
var ButtonTargetEvent = null;
var EnableTimerID = null;
var TargetElement = null;
function Handler_SubmitButtonDisabled(elem) {
    TargetElement = elem;
    ButtonTargetEvent = event.srcElement;
    EnableTimerID = window.setTimeout("HandlerDisabled()", 100);
}
function HandlerDisabled() {
    if (TargetElement == null) {
        for (var i = 0 ; i < ButtonTargetEvent.form.elements.length ; i++)
            ButtonTargetEvent.form.elements[i].disabled = true;
    }
    else {
        TargetElement.disabled = true;
    }
}


/*
creator : Vicky
函式說明:計算某個日期加上天數(秒數，時數，星期，年，月等)
傳入值 : strInterval:TYPE，NumDay:天數，dtDate:日期
傳出值 : 天數
*/
function DateAdd(strInterval, NumDay, dtDate) {
    var strReturn = "";
    $.ajax({
        type: "POST",
        async: false,
        url: "../Common/BLL.aspx/DateAdd",
        data: "{    strInterval : '" + strInterval +
                     "',     NumDay : '" + NumDay +
                     "' ,     dtDate : '" + dtDate + "'} ",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (xmlHttpRequest, error) {
            var m_ErrMessage = xmlHttpRequest.responseText;
            alert(m_ErrMessage);
        },
        success: function (data) {
            strReturn = data.d;
        }
    });

    return strReturn;

}

/*
creator : Vicky
函式說明:計算兩日期差距(秒數，時數，星期，年，月等)
傳入值 : strInterval:TYPE，NumDay:天數，dtDate:日期
傳出值 : 天數
*/
function DateDiff(strInterval, dtStart, dtEnd) {
    oYear1 = dtStart.substr(0, 4);
    oMonth1 = dtStart.substr(4, 2) - 1;//javascript的月份從0開始
    oDay1 = dtStart.substr(6, 2);
    var dtStart = new Date(oYear1, oMonth1, oDay1);
    if (isNaN(dtStart)) dtStart = new Date();

    oYear2 = dtEnd.substr(0, 4);
    oMonth2 = dtEnd.substr(4, 2) - 1;//javascript的月份從0開始
    oDay2 = dtEnd.substr(6, 2);
    var dtEnd = new Date(oYear2, oMonth2, oDay2);
    if (isNaN(dtEnd)) dtEnd = new Date();
    switch (strInterval) {
        case "s": return parseInt((dtEnd - dtStart) / 1000);
        case "n": return parseInt((dtEnd - dtStart) / 60000);
        case "h": return parseInt((dtEnd - dtStart) / 3600000);
        case "d": return parseInt((dtEnd - dtStart) / 86400000);
        case "w": return parseInt((dtEnd - dtStart) / (86400000 * 7));
        case "m": return (dtEnd.getMonth() + 1) + ((dtEnd.getFullYear() - dtStart.getFullYear()) * 12) - (dtStart.getMonth() + 1);
        case "y": return dtEnd.getFullYear() - dtStart.getFullYear();
    }
}
/*
	函式功能 :取得系統日期
	傳入值 : "date","time"
	
	傳出值 : string(YYYYMMDD)
*/
function getServerInfoByClient(dataType, DataFormat) {
    var xmlstr = "";
    try {
        var ReturnValue = "";
        if (dataType == null)
        { ShowError("請傳入第一個取資料型態的參數"); return; }
        if (DataFormat == null && dataType == "date")
            DataFormat = "yyyyMMdd";
        if (DataFormat == null && dataType == "time")
            DataFormat = "hhmmss";

        $.ajax({
            type: "POST",
            async: false,
            url: "../Common/BLL.aspx/ServerInfoByClinetMethod",
            data: "{    p_dataType : '" + dataType +
                         "',     p_DataFormat : '" + DataFormat + "'} ",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function (xmlHttpRequest, error) {
                var m_ErrMessage = xmlHttpRequest.responseText;
                alert(m_ErrMessage);
            },
            success: function (data) {
                ReturnValue = data.d;
            }
        });
    }
    catch (e) {
        return e;
    }
    finally {
        return ReturnValue;
    }
}

/*
creator : Pony
函式說明:計算兩個日期的差異天數
傳入值 : oDate1:終止日期，oDate2:起始日期
傳出值 : 天數
*/
function CACL_DATE(oDate1, oDate2) {
    oYear1 = oDate1.substr(0, 4);
    oMonth1 = oDate1.substr(4, 2) - 1;
    oDay1 = oDate1.substr(6, 2);
    oYear2 = oDate2.substr(0, 4);
    oMonth2 = oDate2.substr(4, 2) - 1;
    oDay2 = oDate2.substr(6, 2);

    var next1 = new Date(oYear1, oMonth1, oDay1);
    var next2 = new Date(oYear2, oMonth2, oDay2);
    var nc = Math.ceil((next1.getTime() - next2.getTime()) / (24 * 60 * 60 * 1000));
    return nc;
}


function CheckStatus() {
    var target = event.srcElement;
    var oRow = target.parentElement.parentElement;
    var i = oRow.rowIndex;
    var objControl = new Object();
    for (var j = 0; j < DetailTable.rows[i].cells.length; j++) {
        for (var k = 0; k < DetailTable.rows[i].cells[j].children.length; k++) {
            if (target.checked) {
                //DetailTable.rows[i].cells[j].children[k].value="";
                DetailTable.rows[i].cells[j].children[k].readOnly = true;
                //objControl.id = DetailTable.rows[i].cells[j].children[k].name;
                //update by samantha --勾選時把原本自己產生的錯誤隱藏起來
                //ErrHandler_Visible_Item(objControl, false);
            }
            else {
                if (DetailTable.rows[i].cells[j].children[k].type == "text" && DetailTable.rows[i].cells[j].children[k].className == 'text') {
                    DetailTable.rows[i].cells[j].children[k].readOnly = false;
                }
                else if (DetailTable.rows[i].cells[j].children[k].type == "text" && DetailTable.rows[i].cells[j].children[k].className == 'number') {
                    DetailTable.rows[i].cells[j].children[k].readOnly = false;
                }
                //objControl.id = DetailTable.rows[i].cells[j].children[k].name;
                //update by samantha --沒勾選時把原本自己產生的錯誤隱藏起來恢復顯現出來
                //ErrHandler_Visible_Item(objControl, true);
            }

        }
    }
}

//---------------------------------------------------------------------------------------

/*
    功能 :	開啟WorkFlow Remark 視窗
    Creator : Titan Xei
    傳入參數 : trans_no = 單據編號 , status = 狀態 , DefaultReMark = 預設備註 
*/
function OpenWorkFlowRemark(trans_no, status, DefaultReMark) {
    var _DialogWidth = "320px";
    var _DialogHeight = "280px";
    var dialogStr = "dialogWidth=" + _DialogWidth + ";dialogHeight=" + _DialogHeight + ";scrollbars=no;center=yes;border=thin;help=no;status=no;resizable=no;";
    var QueryCondition = "trans_no=" + trans_no + "&status=" + status;
    var TargetURL = "../WorkFlowRemark.aspx?"
    try {
        if (trans_no != null && status != null)
            TargetURL = TargetURL + QueryCondition;
        if (DefaultReMark != null)
            TargetURL = TargetURL + "&DefaultReMark=" + DefaultReMark;
        return window.showModalDialog(TargetURL, self, dialogStr, true);
    }
    catch (e) {
        ShowError(e.message);
    }

}


//檢核日期
function check_date(sTmpVal) {
    if (sTmpVal.length < 10) {
        return false;
    }

    for (var i = 0; i < sTmpVal.length; i++) {
        var letter = sTmpVal.substring(i, i + 1);
        if ((letter < "0" || "9" < letter) && letter != "\/") {
            return false;
        }

    }
    for (var i = 0; i < 4; i++) {
        var letterYY = sTmpVal.substring(i, i + 1);
        if (letterYY < "0" || "9" < letterYY) {
            return false;
        }
    }
    var iYear = parseInt(sTmpVal.substring(0, 4));

    for (var i = 5; i < 7; i++) {
        var letterMM = sTmpVal.substring(i, i + 1);
        if (letterMM < "0" || "9" < letterMM) {
            return false;
        }
    }
    var sDummy = sTmpVal.substring(5, 6);
    if (sDummy == "0") {
        sDummy = sTmpVal.substring(6, 7);
    }
    else {
        sDummy = sTmpVal.substring(5, 7);
    }
    var iMonth = parseInt(sDummy);
    if (iMonth < 1 || 12 < iMonth) {
        return false;
    }
    for (var i = 8; i < 10; i++) {
        var letterDD = sTmpVal.substring(i, i + 1);

        if (letterDD < "0" || "9" < letterDD) {
            return false;
        }
    }

    var sDummy1 = sTmpVal.substring(8, 9);
    if (sDummy1 == "0") {
        sDummy1 = sTmpVal.substring(9, 10);
    }
    else {
        sDummy1 = sTmpVal.substring(8, 10);
    }
    var iDay = parseInt(sDummy1);

    if (iDay < 1 || 31 < iDay) {
        return false;
    } else if ((iMonth == 4 || iMonth == 6 || iMonth == 9 || iMonth == 11) && (iDay < 1 || 30 < iDay)) {
        return false;
    } else if (iMonth == 2 && (iDay < 1 || 29 < iDay)) {
        return false;
    } else if (iMonth == 2 && LeapYear(iYear) == false && (iDay < 1 || 28 < iDay)) {
        return false;
    }
    return true;
}
//---------------------------------------------------------------------------------------
// 閏年判斷函式
function LeapYear(intYear) {
    if (intYear % 100 == 0) {
        if (intYear % 400 == 0) { return true; }
    }
    else {
        if ((intYear % 4) == 0) { return true; }
    }
    return false;
}

//取得Server時間
function getServerTime(dataType, DataFormat) {
    var m_ReturnValue = "";
    try {
        if (dataType == null)
        { ShowError("請傳入第一個取資料型態的參數"); return; }
        if (DataFormat == null && dataType == "date")
            DataFormat = "yyyyMMdd";
        if (DataFormat == null && dataType == "time")
            DataFormat = "hhmmss";


        $.ajax({
            type: "POST",
            async: false,
            url: GetLocalPath() + g_Common + "/Query_ServerTime",
            data: "{ p_dataType : '" + dataType + "',p_DataFormat : '" + DataFormat + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function (xmlHttpRequest, error) {
                var m_ErrMessage = xmlHttpRequest.responseText;
                alert(m_ErrMessage);
            },
            success: function (data) {
                m_ReturnValue = data.d;
            }
        });

    }
    catch (e) {
        return e;
    }
    finally {

    }
    return m_ReturnValue;
}

//取得Server時間
function getServerInfoByClient(dataType) {
    var m_ReturnValue = "";
    var DataFormat = "yyyyMMdd";
    try {
        if (dataType == null)
        { ShowError("請傳入第一個取資料型態的參數"); return; }


        $.ajax({
            type: "POST",
            async: false,
            url: GetLocalPath() + g_Common + "/Query_ServerTime",
            data: "{ p_dataType : '" + dataType + "',p_DataFormat : '" + DataFormat + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function (xmlHttpRequest, error) {
                var m_ErrMessage = xmlHttpRequest.responseText;
                alert(m_ErrMessage);
            },
            success: function (data) {
                m_ReturnValue = data.d;
            }
        });

    }
    catch (e) {
        return e;
    }
    finally {

    }
    return m_ReturnValue;
}



//可於高雄機坪(KHCD)內繕打G單
function chk_REF(ISSUETYPE, TYPE, REF1, REF2, DEPT, STORE) {
    try {
        var Message = new Object();
        Message.msg = ''
        if (ISSUETYPE.value == 'A1') {
            if (Trim(REF1.value) != 'INTL' && Trim(REF1.value) != 'DOM') {
                Message.msg = '必需為INTL 或 DOM！'
                Message.object = REF1
            }
        }
        //高雄機坪(KHCD)內繕打G單
        if ((Trim(ISSUETYPE.value) == 'A3') && (Trim(DEPT.value) != 'Y202' && Trim(DEPT.value) != 'Y102' && Trim(DEPT.value) != 'K100' && Trim(DEPT.value) != 'Y204')) {
            Message.msg = '必需是物品採購課(Y202) 或 物品配送課(Y102) 或 服務品課(K100) 或 商品行銷課(Y204)！'
            Message.object = DEPT
        }
        if (TYPE == 'C' && ISSUETYPE.value == 'A3' && Trim(REF2.value) == '') {
            Message.msg = '不可空白'
            Message.object = REF2
        }
        if (Trim(STORE) == 'TEMO' && ISSUETYPE.value != 'C') {
            Message.msg = "待報廢料只接受ISSUE_TYPE為'C'之單據"
            Message.object = ISSUETYPE

        }
    }
    catch (e) {
        ShowError(e.message);
    }
    return Message;
}


function DateAdd1(timeU, byMany, dateObj) {
    var millisecond = 1;
    var second = millisecond * 1000;
    var minute = second * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var year = day * 365;

    var newDate;
    var dVal = dateObj.valueOf();
    switch (timeU) {
        case "ms": newDate = new Date(dVal + millisecond * byMany); break;
        case "s": newDate = new Date(dVal + second * byMany); break;
        case "mi": newDate = new Date(dVal + minute * byMany); break;
        case "h": newDate = new Date(dVal + hour * byMany); break;
        case "d": newDate = new Date(dVal + day * byMany); break;
        case "y": newDate = new Date(dVal + year * byMany); break;
    }
    //var oYear = newDate.getYear();
    var oYear = newDate.getFullYear()
    var oMonth = newDate.getMonth() + 1;
    var oDate = newDate.getDate();
    if (parseInt(oMonth) < 10) {
        oMonth = "0" + oMonth;
    }

    if (parseInt(oDate) < 10) {
        oDate = "0" + oDate;
    }


    var oYMD = String(oYear) + String(oMonth) + String(oDate);
    return oYMD;
}

/*
    清除表格資料
*/
function ClearTableRow(targetTable)
{
    while (targetTable.rows.length > 0)
    {
        targetTable.deleteRow(targetTable.rows.length - 1);
    }
}


function CompareValue(val1, val2, type) {
    var result = new Object();
    if ($("#" + val1).val() == "" && $("#" + val2).val() == "") {
        result.id = "1";
        result.value = '起迄值為空';
    }
    else {
        if ($("#" + val1).val() == "") {
            if (type == "N") {
                if (isNaN($("#" + val1).val()) || isNaN($("#" + val2).val())) {
                    result.id = "3";
                    result.value = '起迄值型態錯誤';
                }
                else {
                    $("#" + val1).val($("#" + val2).val());
                    result.id = "0";
                    result.value = '判斷成功';
                }
            }
            else {
                $("#" + val1).val($("#" + val2).val());
                result.id = "0";
                result.value = '判斷成功';
            }
            return result;
        }
        else if ($("#" + val2).val() == "") {
            if (type == "N") {
                if (isNaN($("#" + val1).val()) || isNaN($("#" + val2).val())) {
                    result.id = "3";
                    result.value = '起迄值型態錯誤';
                }
                else {
                    $("#" + val2).val($("#" + val1).val());
                    result.id = "0";
                    result.value = '判斷成功';
                }
            }
            else {
                $("#" + val2).val($("#" + val1).val());
                result.id = "0";
                result.value = '判斷成功';
            }
            return result;
        }

        if (type == "S") {
            var m_val1 = $("#" + val1).val();
            var m_val2 = $("#" + val1).val();

            if (m_val1 > m_val2) {
                result.id = "2";
                result.value = '起值不可以大於迄值';
            }
            else {
                result.id = "0";
                result.value = '判斷成功';
            }
        }
        else if (type == "N") {
            if (isNaN($("#" + val1).val()) || isNaN($("#" + val2).val())) {
                result.id = "3";
                result.value = '起迄值型態錯誤';
            }
            else {
                if (parseInt($("#" + val1).val(), 10) > parseInt($("#" + val2).val(), 10)) {
                    result.id = "2";
                    result.value = '起值不可以大於迄值';
                }
                else {
                    result.id = "0";
                    result.value = '判斷成功';
                }
            }
        }
        else {
            result.id = "4";
            result.value = '轉換型態錯誤';
        }
    }
    return result;
}

/*
	函式功能 : 加入一個下拉式選單的選項
	傳入值 :  物件編號 , 呈現資料 , 資料值
	傳出值 : null
*/
function addOption(objList, text, value)
{
    var index = objList.options.length;
    objList.options[index] = new Option(text, value);
    objList.selectedIndex = index;
}
//---------------------------------------------------------------------------------------

/*
	函式功能 : 清除下拉式選單的選項
	傳入值 :  物件編號 
	傳出值 : null
*/
function clearOption(objList)
{
    while (objList.options.length != 0)
    {
        objList.options.remove(objList.options.length - 1);
    }
}

function DEPT_FLT_NO_CHANGE()
{
    try
    {
        if ($("#txtDEPT_FLT_NO").val().length > 0)
        {
            if ($("#txtDEPT_FLT_NO").val().substr($("#txtDEPT_FLT_NO").val().length - 1, 1).toUpperCase() == "A")
            {
                if ($("#txtDEPT_FLT_NO").val().substr(0, 1).toUpperCase() == "B")
                {
                    $("#txtDEPT_FLT_NO").val($("#txtDEPT_FLT_NO").val());
                }
                else
                {
                    $("#txtDEPT_FLT_NO").val('BR' + $("#txtDEPT_FLT_NO").val());
                }
            }
            else
            {
                if (isNaN($("#txtDEPT_FLT_NO").val()))
                {
                    $("#txtDEPT_FLT_NO").val($("#txtDEPT_FLT_NO").val());
                }
                else
                {
                    $("#txtDEPT_FLT_NO").val('BR' + $("#txtDEPT_FLT_NO").val());
                }
            }
        }
    }
    catch (e)
    {
        ShowError(e.message);
    }
}



/*
	函式功能: 建立元件
	傳入值 : type,name,size,value,checked,onchange,onclick,IsReadOnly,IsUpper
	傳出值 : string
*/
function CreaterInnerHTML(type, name, size, value, checked, onchange, onclick, IsReadOnly, IsUpper, IsDisabled)
{
    switch (type.toLowerCase()) {
        case "number":
            return "<input type='" + type + "' size='" + size + "' id='" + name + "' name='" + name + "' value='" + value + "' TypeMode='number' onchange='" + onchange + "' onclick='" + onclick + "' class='text' " + (IsReadOnly ? "readonly class='readonly' " : "") + ">";
            break;
        case "input":
            if (!IsReadOnly) {
                if (IsUpper)
                    return "<input type='" + type + "' size='" + size + "' id='" + name + "' name='" + name + "' value='" + value + "' onchange='" + onchange + "' onclick='" + onclick + "' class='text' onBlur='this.value = this.value.toUpperCase();' style='TEXT-TRANSFORM: uppercase'>"
                else
                    return "<input type='" + type + "' size='" + size + "' id='" + name + "' name='" + name + "' value='" + value + "' onchange='" + onchange + "' onclick='" + onclick + "' class='text'>"
            }
            else {
                return "<input type='" + type + "' size='" + size + "' id='" + name + "' name='" + name + "' value='" + value + "' onchange='" + onchange + "' onclick='" + onclick + "' class='aspNetDisabled' style=' border-color:#fff;' readonly detl='Y' >"
            }
            break;
        case "hidden":
            return "<input type='" + type + "' size='" + size + "' id='" + name + "' name='" + name + "' value='" + value + "'>"
            break;
        case "select":
            break;
        case "checkbox":
            if (checked) {
                return "<input type='" + type + "' value='" + value + "' id='" + name + "' name='" + name + "' " + (IsDisabled ? 'disabled="disabled"' : '') + " checked=true onclick='" + onclick + "'>"
            }
            else {
                return "<input type='" + type + "' value='" + value + "' id='" + name + "' name='" + name + "' " + (IsDisabled ? 'disabled="disabled"' : '') + " onclick='" + onclick + "'>"
            }
            break;
        case "radio":
            break;
    }
}
function CreaterInnerHTML1(type,name,size,value,checked,onchange,onclick,IsReadOnly,IsUpper,DataSet) 
{
	var return_str="";
	switch(type.toLowerCase())
	{
		case "select":
		return_str= "<select name='" + name + "' ID='" + name + "' onchange='" + onchange + "' " + (IsReadOnly ? 'disabled="disabled"' : '') + " style='width:100%;'>"
		for (var i = 0; i < DataSet.rows.length; i++) 
		{
			var id=DataSet.rows[i].rAttribute["CODE_ID"];
			var desc=DataSet.rows[i].rAttribute["CODE_SDES"];
			if(value==id) 
			{
				return_str+= "<OPTION selected value="+id+">"
				return_str+= desc+ "</OPTION> "; 
			}
			else
			{
				return_str+= "<OPTION value="+id+">"
				return_str+= desc+ "</OPTION> "; 
			}	
		}        
		return_str+= "</select> "
		break;
    }
    return return_str;
}

function GetTRIndex(p_obj)
{
    var NodeType = p_obj;
    while (NodeType.nodeName != "TR") {
        NodeType = NodeType.parentNode;
    }
    return NodeType.rowIndex;
}


function GetTarget(e)
{
    return $.event.fix(e).target;
}


function Exit() {
    try {
        setTimeout('$(\"#btnExit\")[0].click();', 300);
    }
    catch (e) {
    }

}
